package com.dong.gateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import static org.springframework.cloud.netflix.zuul.filters.support.FilterConstants.*;

/**
 * zuul前置过滤器
 *
 * @author zhaodongchao
 * @date 2020/11/13 11:37
 */
@Component
public class QueryParamPreFilter extends ZuulFilter {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Override
    public String filterType() {
        //指定filter类型，表示这是一个前置过滤器
        return PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        // run before PreDecoration
        return PRE_DECORATION_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return !ctx.containsKey(FORWARD_TO_KEY) // a filter has already forwarded
                && !ctx.containsKey(SERVICE_ID_KEY); // a filter has already determined serviceId
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        logger.info("zuul前置过滤器：当前请求为：{}",request.getRequestURI());
        //如果要路由到完整URL，使用ctx.setRouteHost(url)。
        //要修改路由过滤器转发到的路径，请设置REQUEST_URI_KEY。
        return null;
    }
}
